import React from 'react';
import { Form, Input, Icon, Tag, Tooltip, Button, Popconfirm, Select, Modal, message, Upload } from 'antd';
import { connect } from 'dva';
import { getUpdateServiceProviderUrl } from '../../services/API';
import { getShopId, getLoginToken } from '../../utils/utils';

import styles from './index.less';
// import returnRoules from '.';

const namespace = 'returnRoules';
const { Option } = Select;
/**
 *  登录界面
 */
@connect(({ loading, returnRoules }) => ({
  rouleId: returnRoules.rouleId,
  getAllStateList: returnRoules.getAllStateList,
  serviceProvidersList: returnRoules.serviceProvidersList,
  getZipCodeData: returnRoules.getZipCodeData,
  //控制状态，绑定事件
  submitting: loading.effects['login/doLogin']
}))
@Form.create()
class StepFour extends React.Component {
  state = {
    visible: false,
    tags: [],
    inputVisible: false,
    inputValue: '',
    uploading: false,
    curItem: null //当前编服务信息
  };

  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // values.states = values.states[0];
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        values.states = values.states.join(',');
        values.zipCodes = values.zipCodes.join(',');
        this.props.dispatch({
          type: `${namespace}/addProviderInfo`,
          payload: {
            id: this.props.rouleId,
            shopId: userInfo.shopId,
            ...values
          },
          callback: () => {
            // this.props.dispatch({
            //   type:`${namespace}/save`,
            //   payload:{
            //     stepCurrent:4
            //   }
            // })
          }
        });
      }
    });
    this.setState({
      visible: false
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false
    });
  };
  handleSelectChange = value => {
    console.log(value);
    this.props.form.setFieldsValue({
      note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`
    });
  };

  // 气泡
  confirm = e => {
    console.log(e);
    this.props.dispatch({
      type: `${namespace}/deleteProviderInfo`,
      payload: {
        id: e.id
      }
    });
  };
  // tag
  handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    console.log(tags);
    this.setState({ tags });
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { tags } = this.state;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    console.log(tags);
    this.setState({
      tags,
      inputVisible: false,
      inputValue: ''
    });
  };
  saveInputRef = input => (this.input = input);

  // 保存数据
  handleSubmit = e => {
    e.preventDefault();
    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        stepCurrent: 4
      }
    });
    this.props.dispatch({
      //查询规则详情
      type: `${namespace}/fetchRules`,
      payload: {
        id: this.props.rouleId
      }
    });
  };
  render() {
    const { getFieldDecorator } = this.props.form;

    const { getAllStateList, serviceProvidersList, getZipCodeData } = this.props;
    const { visible, tags, inputVisible, inputValue } = this.state;
    return (
      <div className={styles.stepFour}>
        <div className={styles.step4oper}>
          <div className={styles.step4operMain}>
            <Button
              htmlType="submit"
              type="primary"
              icon="plus"
              onClick={() => {
                this.setState({
                  visible: true
                });
              }}
            >
              Add trucking provider
            </Button>
          </div>
          <div>
            <Button
              style={{ marginRight: 10 }}
              onClick={() => {
                window.open('./truckingprovider.xlsx');
              }}
            >
              Download template
            </Button>
            <Upload
              name="excelFile"
              action={getUpdateServiceProviderUrl()}
              headers={{
                authorization: getLoginToken() || ''
              }}
              showUploadList={false}
              beforeUpload={() => {
                this.setState({
                  uploading: true
                });
                return true;
              }}
              data={{
                shopId: getShopId()
              }}
              onChange={info => {
                if (info.file.status === 'done' || info.file.status === 'error') {
                  this.setState({
                    uploading: false
                  });
                  if (info.file.status === 'done') {
                    message.success('Upload succeeded');
                    this.props.dispatch({
                      //查询规则详情
                      type: `${namespace}/getAllServiceProvider`,
                      payload: {}
                    });
                  }
                }
              }}
            >
              <Button disabled={this.state.uploading}>Upload attachment</Button>
            </Upload>
          </div>
        </div>
        <div className={styles.step4Content}>
          {serviceProvidersList.length > 0 &&
            serviceProvidersList.map(ditem => {
              return (
                <div key={ditem.id} className={styles.providerItem}>
                  <div className={styles.providerItemHead}>
                    <h2>{ditem.carrierName || 'The Return Company'}</h2>
                    <div className={styles.providerItemOper}>
                      <Button
                        icon="edit"
                        onClick={() => {
                          this.setState({
                            visible: true,
                            curItem: ditem
                          });
                          this.props.form.setFieldsValue({
                            ...ditem,
                            states: ditem ? ditem.states.split(',') : ''
                          });
                        }}
                      >
                        Edit
                      </Button>
                      <Popconfirm
                        title="Are you sure delete this task?"
                        onConfirm={() => this.confirm(ditem)}
                        okText="Yes"
                        cancelText="No"
                      >
                        <Button icon="delete">Delete</Button>
                      </Popconfirm>
                    </div>
                  </div>
                  <div className={styles.providerItemContent}>
                    <div className={styles.providerItemState}>
                      <h3>States</h3>
                      {ditem.states && ditem.states.indexOf(',') > -1 ? (
                        <div>
                          {ditem.states
                            .split(',')
                            .filter(a => a)
                            .map(item => (
                              <span key={item} className={styles.providerItemState}>
                                {item}
                              </span>
                            ))}
                        </div>
                      ) : (
                        <div className={styles.providerItemStates}>{ditem.states}</div>
                      )}
                    </div>
                    <div className={styles.providerItemZipCode}>
                      <h3>Zip code</h3>
                      <div className={styles.detailNum}>
                        {(ditem.zipCode && ditem.zipCode.indexOf(',') > -1 && ditem.zipCode.split(',').length - 1) || 1}{' '}
                        zip codes
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
        </div>

        <div className={styles.footList}>
          <Button onClick={e => this.handleSubmit(e, 'save')} className={styles.formBtn}>
            Save
          </Button>
          <Button onClick={e => this.handleSubmit(e, 'save')} className={styles.formBtn}>
            Next
          </Button>
        </div>
        <Modal
          title="Add new trucking service provider"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText={'Save'}
        >
          <Form onSubmit={this.handleSubmit} className="login-form" hideRequiredMark={true}>
            <Form.Item label="Carrier name">
              {getFieldDecorator('carrierName', {
                rules: [{ required: true, message: 'Please input your carrierName!' }]
              })(<Input placeholder="carrierName" />)}
            </Form.Item>
            <Form.Item label="States">
              {getFieldDecorator('states', {
                rules: [{ required: true, message: 'Please select!' }]
              })(
                <Select
                  mode="tags"
                  onChange={value => {
                    console.log(value, 'value');
                    this.props.dispatch({
                      type: `${namespace}/getZipCodeByStateBatch`,
                      payload: {
                        state: value.join(',')
                      }
                    });
                  }}
                  onFocus={() => {
                    if (getAllStateList.length > 0) return;
                    this.props.dispatch({
                      type: `${namespace}/getAllStateList`
                    });
                  }}
                >
                  {getAllStateList.length > 0 &&
                    getAllStateList.map(item => <Option key={item.abbreviation}>{item.abbreviation}</Option>)}
                </Select>
              )}
            </Form.Item>
            <Form.Item label="Zip codes" style={{ marginBottom: 0 }}>
              {getFieldDecorator('zipCodes', {
                rules: [{ required: true, message: 'Please input!' }],
                initialValue: getZipCodeData ? getZipCodeData : ''
              })(
                <div className="tagList">
                  {tags.concat(getZipCodeData).map((tag, index) => {
                    const isLongTag = tag.length > 20;
                    const tagElem = (
                      <Tag key={tag} closable={index !== 0} onClose={() => this.handleClose(tag)}>
                        {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                      </Tag>
                    );
                    return isLongTag ? (
                      <Tooltip title={tag} key={tag}>
                        {tagElem}
                      </Tooltip>
                    ) : (
                      tagElem
                    );
                  })}
                  {inputVisible && (
                    <Input
                      ref={this.saveInputRef}
                      type="text"
                      size="small"
                      style={{ width: 78 }}
                      value={inputValue}
                      onChange={this.handleInputChange}
                      onBlur={this.handleInputConfirm}
                      onPressEnter={this.handleInputConfirm}
                    />
                  )}
                  {!inputVisible && (
                    <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                      <Icon type="plus" /> New Tag
                    </Tag>
                  )}
                </div>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default StepFour;
